/*
 * @(#)NIOResponder.java	1.0 Mar 8, 2008
 *
 *	The MIT License
 *
 *	Copyright (c) 2008 Malachi de AElfweald <malachid@gmail.com>
 *
 *	Permission is hereby granted, free of charge, to any person obtaining a copy
 *	of this software and associated documentation files (the "Software"), to deal
 *	in the Software without restriction, including without limitation the rights
 *	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *	copies of the Software, and to permit persons to whom the Software is
 *	furnished to do so, subject to the following conditions:
 *
 *	The above copyright notice and this permission notice shall be included in
 *	all copies or substantial portions of the Software.
 *
 *	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *	THE SOFTWARE.
 */
package org.eoti.net.nio;

import static org.eoti.util.log.LogUtil.log;

import java.nio.channels.SelectionKey;
import static java.nio.channels.SelectionKey.OP_READ;
import java.nio.channels.SocketChannel;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
import static java.util.concurrent.TimeUnit.MILLISECONDS;

public class NIOResponder<ATTACHMENT>
		extends Thread
{
	protected NIOServer<ATTACHMENT> server;
	protected boolean	dead = true;

	public NIOResponder(NIOServer<ATTACHMENT> server)
	{
		super("NIOResponder");
		this.server = server;
		this.dead = false;
	}

	public void die()
	{
		this.dead = true;
	}

	public void run()
	{
		while(!dead)
		{
			try{
				/**
			     * Timeout may not be necessary, but thought this might be a
			     * little more likely to prevent deadlock.
			     */
				LinkedBlockingQueue<SocketChannel> connections = server.getConnections();
				while(!connections.isEmpty())
				{
					SocketChannel sc = connections.poll(server.getTimeoutMS(), MILLISECONDS);
					registerNewChannel(sc);
				}

		    	if(server.getReadSelector().select(server.getTimeoutMS()) > 0)
		    		acceptPendingRequests();
		    }catch(Exception e){
				log("NIOResponder: Error responding to incoming connections", e);
		    }
		}
	}

	protected void registerNewChannel(SocketChannel connection)
	throws NIOException
	{
		try{
			connection.configureBlocking(false);
			connection.register(server.getReadSelector(), OP_READ, server.getService().createEmptyAttachment());
	    }catch(Exception e){
	    	throw new NIOException(e);
	    }
	}

	protected void acceptPendingRequests()
			throws NIOException
	{
		Set<SelectionKey> readyKeys = server.getReadSelector().selectedKeys();
		for(SelectionKey key : readyKeys)
		{
			readyKeys.remove( key );
			server.getService().readRequest(key);
		}
	}
}
